package com.weizhong.update.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.weizhong.update.appdb.DBManager;
import com.weizhong.update.model.AppEntity;
import com.weizhong.update.model.AppServerEntity;
import com.weizhong.update.receiver.BootReceiver;
import com.weizhong.update.service.AppUpdateDownloadListener;
import com.weizhong.xml.LocalConfigInfo;
import com.weizhong.xml.PullParseService;

import android.R.integer;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Build;
import android.os.Environment;
import android.os.Environment.UserEnvironment;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.WZAccessServiceManager;
import android.os.WZBubbleUserInfo;
import android.text.TextUtils;
import android.util.Log;

/**
 * 预装应用更新逻辑
 * @author wangbin
 *
 */
public class AppUpdateDetail {
	private static final String TAG = "AppUpdateDetail";
	//应用更新时间
	long update_time = 0;
	//服务器端更新时间
	long lastupdate_time = 0;
	Context context;
	public static AppServerEntity entity = null;
	//app 更新、卸载
	AppManager appManager;
	// 更新配置文件的路径
	public final String update_config_path = Constances.update_dir + "/appconfig.xml";

	//数据库更新
	public DBManager dbManager;
	public AppUpdateDetail(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
        appManager = null;
        dbManager = new DBManager(context);
    }

	/**
	 * 
	 * 获得本地系统版本
	 */
	public String getLocSysteVersion() {
		
		return SystemProperties.get("ro.product.version");

	}

	private String getLocSystemModel() {

		return Build.MODEL;

	}

	/**
	 * 获取服务器端更新时间
	 * @return
	 */
	public String getLastUpdateTime(){
		
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		lastupdate_time = preferences.getLong("last_update_time", lastupdate_time);
		return Long.toString(lastupdate_time);
	}
	
	/**
	 * 设置服务器端更新时间
	 */
	public void setLastUpdateTime(long last_update_time){
		lastupdate_time = last_update_time;
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		Editor editor=preferences.edit();
		editor.putLong("last_update_time", last_update_time);
		editor.commit();
	}

	/**
	 * 获取安装模式
	 * @return
	 */
	public int getInstallMode(){
		
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		return (preferences.getInt("install_mode",0));
	}
	
	public void setInstallMode(int updateMode){
		Log.i(TAG, "setInstallMode : " + updateMode);
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		Editor editor=preferences.edit();
		editor.putInt("install_mode", updateMode);
		editor.commit();
	}

	/**
	 * 获取更新xml配置文件路径
	 * @return
	 */
	public String getAppConfigPath() {

		if (getSdcardPath() == null)
			return null;
		return getSdcardPath() + update_config_path;
	}

	/**
	 * 生成应用更新xml配置文件
	 * @param entity
	 */
	public void buildXML(AppServerEntity entity) {
		Logger.i(TAG, "buildXML");

		File dir = new File(Constances.update_dir);
		if (!dir.exists()) {
			Logger.i(TAG, "build dir:" + dir.getName());
			dir.mkdirs();
		}

        File file = new File(getAppConfigPath());
        if (!file.exists()) {
			try {
				Logger.i(TAG, "build file:" + file.getName());
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        }

		if (!file.exists())
        return;

		FileOutputStream outputStream = null;

		try {
			outputStream = new FileOutputStream(file);
			PullParseService.buildAppXML((List<AppEntity>)entity.getAppList(),outputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 检查服务器是否有更新
	 * @param context
	 * @param updateCheckUrl
	 * @return
	 */
	public int ServerCheckUpdate(Context context, String updateCheckUrl) {

		int retValue = 0;
		
		Log.i(TAG, "ServerCheckUpdate");
		
		if (getAppSize() > 0){
			if (isAppUpdateSuccess() == false){
				Log.i(TAG, "ServerCheckUpdate: 上次应用更新未完成，返回");
				return 2;
			}else {
				setUpdateTime(Long.valueOf(getLastUpdateTime()));
				clear();
				Log.i(TAG, "ServerCheckUpdate: 上次应用更新已完成，返回");
				return 0;
			}
		}
		
		NameValuePair version = new BasicNameValuePair("cl_version",

		getLocSysteVersion());

		NameValuePair system_model = new BasicNameValuePair("system_model",

		getLocSystemModel());
		
		WZBubbleUserInfo userInfo = WZAccessServiceManager.getBubbleUserFullInfo();
		
		NameValuePair bubble_id = new BasicNameValuePair("bubble_id",

		userInfo.getUserID());
		
		NameValuePair area_code = new BasicNameValuePair("area_code",

		userInfo.getAreaCode());
		
		NameValuePair last_updatetime = new BasicNameValuePair("last_updatetime",
		//TODO: FOR TEST
		getUpdateTime());
		
		String result = HttpTool.httpPostRequest(updateCheckUrl, bubble_id,area_code,
		version,system_model,last_updatetime);

		if (!TextUtils.isEmpty(result)) {
			AppServerEntity newEntity = JsonTool.parseAppJson(result);
			if (newEntity != null){
				boolean isNeedUpdate = false;
				//如果有应用需要更新
				if(newEntity.getAppList().size() > 0){
					
					for(int i = 0;i<newEntity.getAppList().size();i++){
						PackageManager pm = context.getPackageManager();
						PackageInfo info;
						long appVersion = 0;
						if(newEntity.getAppList().get(i).getPackageName() != null){
							try {
								info = pm.getPackageInfo(newEntity.getAppList().get(i).getPackageName(), 0);
								if(info != null){
									appVersion = (long)info.versionCode;
									Logger.i(TAG, newEntity.getAppList().get(i).getPackageName()
											+ "app version: " + appVersion);
								}
							} catch (NameNotFoundException e) {
								e.printStackTrace();
								appVersion = -1;
								Logger.i(TAG, newEntity.getAppList().get(i).getPackageName() + 
										"app version: not found " + appVersion);
							}
						}
						//此版本较新则更新模式判断
						if(newEntity.getAppList().get(i).getAction() == 1){
							if(newEntity.getAppList().get(i).getVerCode() > appVersion){
								isNeedUpdate = true;
								break;
							}
						}else if(newEntity.getAppList().get(i).getAction() == 2){
							if(newEntity.getAppList().get(i).getVerCode() > appVersion){
								isNeedUpdate = true;
								break;
							}
						}else if(newEntity.getAppList().get(i).getAction() == 3){
							isNeedUpdate = true;
						}else if(newEntity.getAppList().get(i).getAction() == 4){
							if(newEntity.getAppList().get(i).getVerCode() == appVersion){
								isNeedUpdate = true;
								break;
							}
						}
					}
					
					if(!isNeedUpdate){
						if(Long.valueOf(getUpdateTime()) < newEntity.getLastUpdateTime()){
							setLastUpdateTime(newEntity.getLastUpdateTime());
							setUpdateTime(Long.valueOf(getLastUpdateTime()));
						}
						retValue = 0;
						return retValue;
					}
					
					//如果上次更新时间小于newEntity时间，则更新
					if(Long.valueOf(getUpdateTime()) < newEntity.getLastUpdateTime()){
						//TODO:存储数据库之前判断是否需要更新
						entity = newEntity;
						if (entity.getResultCode() == 1){
							//清除数据库
							deleteDBRecords();
							dbManager.add(entity.getAppList());
							retValue = 1;
							setLastUpdateTime(entity.getLastUpdateTime());
							setInstallMode(entity.getInstallMode());
						}
					}
				}
			}
		}
		int updateMode = -1;
		if (entity != null){
			updateMode = entity.getInstallMode();
		}

		return retValue;
	}
	
	
	/**
	 * 获取应用更新时间
	 * @return
	 */
	public String getUpdateTime(){
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		update_time = preferences.getLong("update_time", update_time);
		return Long.toString(update_time);
	}

	/**
	 * 设置应用更新时间
	 * @param update_time
	 */
	public void setUpdateTime(long update_time) {
		SharedPreferences preferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
		Editor editor=preferences.edit();
		editor.putLong("update_time", update_time);
		editor.commit();
	}
	
	/**
	 * 删除所有apk文件
	 */
    public void deleteFiles(){
    	UserEnvironment userEnvironment = new UserEnvironment(UserHandle.myUserId());
    	File sdcardPath = userEnvironment.getExternalStorageDirectory();
    	String fileAbsolutePath = sdcardPath.getAbsolutePath() +  "/data/system/update/";
    	Log.i(TAG, "fileAbsolutePath: " + fileAbsolutePath);
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();
 
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                // 判断是否为apk结尾
                if (filename.trim().toLowerCase().endsWith(".apk")) {
                    subFile[iFileLength].delete();
                }
            }
        }
    }
	
	/**
	 * 清除缓存
	 */
	public void clear() {
		Logger.i(TAG, "clear all data");
		
		AppEntity appEntity;
		Cursor c = queryTheCursor();
		while (c.moveToNext()) {
			appEntity = cursorToAppEntity(c);

			if (appEntity != null){
				String downloadUrl = appEntity.getApkPath();
		        String fileName = appEntity.getPackageName() + ".apk";;
		        String dirPath = getSdcardPath() + Constances.update_dir;
		        File file = new File(dirPath+"/"+fileName);
		        Log.i(TAG, "delete: " + fileName);
		        if (file.exists()){
		        	file.delete();
		        }
			}

			//clear config file
			File config = new File(getAppConfigPath());
	        if (config.exists()){
	        	config.delete();
	        }
		}
		
		deleteFiles();
		
		//清除数据库所有下载记录
		deleteAllDownload();
		
		//清除数据库记录
		deleteDBRecords();
		
		BootReceiver.isReceiveAppUpdateRequest = 0;
	}
	
	/**
	 * 更新应用
	 * @param appEntity
	 */
	public void update(AppEntity appEntity){
		if(appEntity.getAction() == 1){ //1=此版本较新则更新
			Logger.i(TAG, "1=此版本较新则更新");
			
			//TODO: 判断下载版本是否较新
	        String fileName = appEntity.getPackageName() + ".apk";
	        String dirPath = getSdcardPath()+Constances.update_dir;
	        
	        PackageManager pm = context.getPackageManager();  

	        PackageInfo info = pm.getPackageArchiveInfo(dirPath+"/"+fileName, PackageManager.GET_ACTIVITIES);  
	       
	        String packageName = null;
	        long curVersion = 0,version = 0;
	        
	        if(info != null){  
	            
	        	ApplicationInfo appInfo = info.applicationInfo;  

	            packageName = appInfo.packageName;  //得到安装包名称

	            version= (long)info.versionCode;       //得到版本信息 
	        }
	        
	        try {
				info = pm.getPackageInfo(packageName, 0);
				if(info != null){
					curVersion = (long)info.versionCode;
					Logger.i(TAG, "app curVersion: " + curVersion + " version: " + version);
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				curVersion = 0;
				e.printStackTrace();
			}

	        if (version > curVersion){
	        	Logger.i(TAG, "version > curVersion we will update it");
		        if (appManager == null){
		        	appManager = new AppManager(context);
		        }
/*                //判断是否更新图标
		        if(appEntity.getIsDeskTop() == 1){
		        	appManager.setShortCut(appEntity.getPackageName(), 1);
		        }else {
		        	if(appManager.hasShortCut(appEntity.getPackageName()) == 1){
		        		appManager.setShortCut(appEntity.getPackageName(), 1);
		        	}else {
		        		appManager.setShortCut(appEntity.getPackageName(), 0);
					}
				}*/

		        appManager.installapp(dirPath+"/"+fileName,false);
	        }else{
	        	Logger.i(TAG, "version <= curVersion we will not update it");
				appEntity.setUpdateSuccess(true);
				updateUpdateResult(appEntity);
	        }
		}else if (appEntity.getAction() == 2) {
			Logger.i(TAG, "2=强制更新到此版本");
			String fileName = appEntity.getPackageName() + ".apk";
	        String dirPath = getSdcardPath()+Constances.update_dir;

	        if (appManager == null){
	        	appManager = new AppManager(context);
	        }

	        appManager.installapp(dirPath+"/"+fileName,true);
		}else if (appEntity.getAction() == 3) {
			Logger.i(TAG, "3=卸载应用");
			PackageManager pm = context.getPackageManager();
			PackageInfo info;
			
			long version = 0;
			try {
				info = pm.getPackageInfo(appEntity.getPackageName(), 0);
				if(info != null){
					version = (long)info.versionCode;
					Logger.i(TAG, "app version: " + version);
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				version = -1;
			}
	        
			if(version == -1){
				Log.i(TAG, appEntity.getPackageName() + "未发现，不需要卸载");
				appEntity.setUpdateSuccess(true);
				updateUpdateResult(appEntity);
			}else {
		        if (appManager == null){
		        	appManager = new AppManager(context);
		        }

		        appManager.deleteapp(appEntity.getPackageName());
			}

		}else if (appEntity.getAction() == 4) {
			Logger.i(TAG, "4=仅卸载当前版本");
			PackageManager pm = context.getPackageManager();
			PackageInfo info;
			long version = 0;
			try {
				info = pm.getPackageInfo(appEntity.getPackageName(), 0);
				if(info != null){
					version = (long)info.versionCode;
					Logger.i(TAG, "app version: " + version);
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				version = -1;
			}
			//卸载当前版本
			if(version == appEntity.getVerCode()){
		        if (appManager == null){
		        	appManager = new AppManager(context);
		        }
		        appManager.deleteapp(appEntity.getPackageName());
			}else {
		        if (appManager == null){
		        	appManager = new AppManager(context);
		        }
				appEntity.setUpdateSuccess(true);
				updateUpdateResult(appEntity);
			}
		}
	}
	
	/**
	 * 下载完成,应用列表更新
	 * @return
	 */
	public boolean updateApp(){
		Logger.i(TAG, "updateApp");
		
		Cursor c = queryTheCursor();
		AppEntity appEntity;
		while (c.moveToNext()) {
			appEntity = cursorToAppEntity(c);
			if(appEntity != null){
				//如果该应用已经更新，则跳过
				if(hasUpdateDone(appEntity.getPackageName())){
					continue;
				}else {
					update(appEntity);
				}
			}else {
				Logger.i(TAG, "entity is NULL!");
			}
		}
		return true;
	}
	
	/**
	 * 
	 * 获得sdcard 路径
	 * 
	 * 
	 * 
	 * @return
	 */

	public String getSdcardPath() {

		if (!Environment.getExternalStorageState().equals(

		Environment.MEDIA_MOUNTED))

			return "";

		UserEnvironment userEnvironment = new UserEnvironment(UserHandle.myUserId());
		File sdcardPath = userEnvironment.getExternalStorageDirectory();

		return sdcardPath.getAbsolutePath();

	}

	/**
	 * 根据配置文件初始化 AppServerEntity
	 */
	public void initAppServerEntity() {
		File file = new File(getSdcardPath() + update_config_path);
		if (!file.exists()) {
			return;
		}

		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			List<AppEntity> configList = PullParseService.getAppInfos(inputStream);

			if (configList != null && configList.size() > 0) {
				if(entity == null){
					entity = new AppServerEntity();
				}
				entity.setAppList(configList);
			}

			//获取更新时间
			long updateTime = Long.valueOf(getLastUpdateTime());
			entity.setLastUpdateTime(updateTime);
			
			//设置更新模式
			entity.setInstallMode(getInstallMode());

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public AppServerEntity  getAppServerEntity() {
		return entity;
	}
	
	public void setAppServerEntity(AppServerEntity entity) {
		this.entity = entity;
	}
	
	public int getAppEntityNum() {
		if(entity != null){
			return entity.getAppList().size();
		}
		return 0;
	}
	
	public void startSystemUi() {
		Intent intent = new Intent();
		intent.setComponent(new ComponentName("com.android.systemui",
				"com.android.systemui.SystemUIService"));
		context.startServiceAsUser(intent, UserHandle.OWNER);
	}
	
	//存储app更新信息
	/**
	 * 遍历appServerEntity,将获取的更新apk信息存储到数据库
	 * @param appServerEntity
	 */
	public void add(AppServerEntity appServerEntity){
		dbManager.add(appServerEntity.getAppList());
	}

	/**
	 * 遍历数据库
	 * @return cursor
	 */
	public Cursor queryTheCursor(){
		Cursor c = dbManager.queryTheCursor();
		return c;
	}
	
	/**
	 * 获取下次需下载的appEntity
	 * @return
	 */
	public AppEntity findDownloadAppEntity(){
		Cursor c = queryTheCursor();
        while (c.moveToNext()) {
        	String packageName = c.getString(c.getColumnIndex("packageName"));
        	Log.i(TAG,"findDownloadAppEntity: " + packageName + " : "+ c.getInt(c.getColumnIndex("downloadSuccess")));
        	//find next appentity to download
        	if(c.getInt(c.getColumnIndex("downloadSuccess")) == 1){
        		Log.i(TAG,packageName + "downloadsuccess");
        		continue;
        	}else {
        		//TODO:增加对更新当前版本的判断
				if((c.getInt(c.getColumnIndex("action")) == 3) || (c.getInt(c.getColumnIndex("action")) == 4)){
					Log.i(TAG,packageName + "卸载，不需要下载");
					if(entity != null){
						int i = 0;
						for(;i<entity.getAppList().size();i++){
							if(entity.getAppList().get(i).getPackageName().equals(packageName)){
								entity.getAppList().get(i).setDownloadSuccess(true);
							}
						}
					}
					//更新数据库
					AppEntity appEntity = new AppEntity();
					appEntity.setPackageName(packageName);
					appEntity.setDownloadSuccess(true);
					updateDownloadResult(appEntity);
					continue;
				}else if((c.getInt(c.getColumnIndex("action")) == 1) || (c.getInt(c.getColumnIndex("action")) == 2)){
					long verCode = Long.valueOf(c.getString(c.getColumnIndex("verCode")));

					PackageManager pm = context.getPackageManager();
					PackageInfo info;
					long version = 0;
					try {
						info = pm.getPackageInfo(packageName, 0);
						if(info != null){
							version = (long)info.versionCode;
							Logger.i(TAG, packageName + "app version: " + version + "version code: " + verCode);
						}
					} catch (NameNotFoundException e) {
						e.printStackTrace();
						version = -1;
						Logger.i(TAG, packageName + "app version: not found " + version);
					}
					if (version >= verCode){
						Log.i(TAG, "当前系统大于等于该版本应用，无需下载");
						//更新数据库
						AppEntity appEntity = new AppEntity();
						appEntity.setPackageName(packageName);
						appEntity.setDownloadSuccess(true);
						appEntity.setUpdateSuccess(true);
						updateDownloadResult(appEntity);
						updateUpdateResult(appEntity);
					}else {
						Logger.i(TAG, packageName + "download id " + c.getInt(c.getColumnIndex("downloadid")));
						AppEntity appEntity;
						appEntity = cursorToAppEntity(c);
						return appEntity;
					}
				}
			}
        }
        return null;
	}

	/**
	 * 删除数据库记录
	 */
	public void deleteDBRecords() {
		Log.i(TAG," deleteDBRecords");
		dbManager.deleteAllAppEntity();
	}
	
	/**
	 * 更新app下载结果
	 * @param appEntity
	 */
	public void updateDownloadResult(AppEntity appEntity) {
		Log.i(TAG,appEntity.getPackageName() + "updateDownloadResult");
		dbManager.updateDownloadResult(appEntity);
	}
	
	/**
	 * 保存更新结果
	 * @param appEntity
	 */
	public void updateUpdateResult(AppEntity appEntity) {
		Log.i(TAG,appEntity.getPackageName() + "updateUpdateResult");
		dbManager.updateUpdateResult(appEntity);
	}
	
	/**
	 * 保存app对应下载id
	 * @param appEntity
	 */
	public void updateDownloadID(AppEntity appEntity) {
		Log.i(TAG,appEntity.getPackageName() + "updateDownloadID" + appEntity.getDownloadID());
		dbManager.updateDownloadID(appEntity);
	}
	
	/**
	 * 保存app是否创建桌面图标
	 * @param appEntity
	 */
	public void updateDesktop(AppEntity appEntity) {
		Log.i(TAG,appEntity.getPackageName() + "updateDesktop");
		dbManager.updateDownloadID(appEntity);
	}
	
	/**
	 * 获取本次更新全部下载大小
	 * @return
	 */
	public int getDownloadSize() {
		int size = 0;
		Cursor c = queryTheCursor();

		while (c.moveToNext()) {
			String packageName = c.getString(c.getColumnIndex("packageName"));
			if((c.getInt(c.getColumnIndex("action")) == 1) || (c.getInt(c.getColumnIndex("action")) == 2)){
				
				long verCode = Long.valueOf(c.getString(c.getColumnIndex("verCode")));

				PackageManager pm = context.getPackageManager();
				PackageInfo info;
				long version = 0;
				try {
					info = pm.getPackageInfo(packageName, 0);
					if(info != null){
						version = (long)info.versionCode;
						Logger.i(TAG, packageName + "app version: " + version);
					}
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					version = -1;
					Logger.i(TAG, packageName + "app version: not found " + version);
				}
				if (version < verCode){
					Log.d(TAG,packageName +" : version " + version + " versionCode: " + verCode);
					size += (Integer.valueOf(c.getString(c.getColumnIndex("apkSize"))));
				}

			}
		}
		Log.i(TAG,"getDownloadSize() is: " + size);
		return size;
	}
	
	/**
	 * 获取本次更新应用个数
	 * @return
	 */
	public int getAppSize(){
		int i = 0;
		Cursor c = queryTheCursor();
		while (c.moveToNext()) {
			i += 1;
		}
		return i;
	}
	
	/**
	 * 判断该应用是否需要添加桌面图标
	 * @param packageName
	 * @return
	 */
	public boolean isAddDesktop(String packageName){
		int result = 0;
		Cursor c = queryTheCursor();
		
		while (c.moveToNext()) {
			if(c.getString(c.getColumnIndex("packageName")).equals(packageName)){
				result = c.getInt(c.getColumnIndex("isDeskTop"));
				if(result == 1){
					return true;
				}else{
					return false;
				}
			}
		}

		return false;
	}
	
	/**
	 * 判断该应用是否需要添加桌面图标
	 * @param packageName
	 * @return
	 */
	public boolean hasUpdateDone(String packageName){
		Log.i(TAG, "hasUpdateDone");

		int result = 0;
		Cursor c = dbManager.queryPackageCursor(packageName);
		
		while (c.moveToNext()) {
			result = c.getInt(c.getColumnIndex("updateSuccess"));
			Log.i(TAG,packageName + "result is : " + result);
			if(result == 1){
				return true;
			}else {
				return false;
			}
		}

		return false;
	}
	
	/**
	 * 将遍历cursor转化为appEntity
	 * @param c
	 * @return
	 */
	public AppEntity cursorToAppEntity(Cursor c){
		AppEntity appEntity = new AppEntity();
		
		appEntity.setID(c.getInt(c.getColumnIndex("bubbleid")));
		
		appEntity.setAppName(c.getString(c.getColumnIndex("appName")));
		
		appEntity.setPackageName(c.getString(c.getColumnIndex("packageName")));
		
		appEntity.setApkSize(Long.valueOf(c.getString(c.getColumnIndex("apkSize"))));
		
		appEntity.setApkPath(c.getString(c.getColumnIndex("apkPath")));
		
		appEntity.setVerName(c.getString(c.getColumnIndex("verName")));
		
		appEntity.setVerCode(Long.valueOf(c.getString(c.getColumnIndex("verCode"))));
		
		appEntity.setAction(c.getInt(c.getColumnIndex("action")));
		
		appEntity.setUpdateDes(c.getString(c.getColumnIndex("updateDes")));
		
		appEntity.setAppType(c.getInt(c.getColumnIndex("appType")));
		
		appEntity.setIsDeskTop(c.getInt(c.getColumnIndex("isDeskTop")));
		
		if(c.getInt(c.getColumnIndex("downloadSuccess")) == 0){
			appEntity.setDownloadSuccess(false);
		}else {
			appEntity.setDownloadSuccess(true);
		}
		
		if(c.getInt(c.getColumnIndex("updateSuccess")) == 0){
			appEntity.setUpdateSuccess(false);
		}else {
			appEntity.setUpdateSuccess(true);
		}
		
		appEntity.setDownloadID(c.getInt(c.getColumnIndex("downloadid")));
		
		return appEntity;
	}
	
	/**
	 * 判断本次更新是否完成
	 * @return
	 */
	public boolean isAppUpdateSuccess(){
		Cursor c = queryTheCursor();

		Log.d(TAG, "app update size: " + c.getCount());
		while (c.moveToNext()) {
			if((c.getInt(c.getColumnIndex("updateSuccess")) == 0)){
				Log.i(TAG, c.getString(c.getColumnIndex("packageName")) + "update fail");
				Log.i(TAG, "AppUpdate FAIL!");
				return false;
			}
		}
		Log.i(TAG, "AppUpdate Success!");
		return true;
	}

	/**
	 * 更新下载监听记录
	 */
	//TODO:
	public void setDownloadIDToMap(){
		Cursor c = queryTheCursor();

		while (c.moveToNext()) {
			int downloadid = c.getInt((c.getColumnIndex("downloadid")));
			if( downloadid > 0){
				if(c.getInt(c.getColumnIndex("downloadSuccess")) == 1){
					String packagename = c.getString(c.getColumnIndex("packageName"));
					AppUpdateDownloadListener.hashMap.put(packagename, (long) downloadid);
					AppUpdateDownloadListener.StatusMap.put(packagename, true);
				}
			}
		}
	}
	
	/**
	 * 删除数据库中所有下载ID
	 */
	public void deleteAllDownload(){
		//初始化DownloadManager
		Log.i(TAG, "deleteAllDownload");
		DownloadManager mgr;
		mgr = (DownloadManager)context.getSystemService("download");
		
		Cursor c = queryTheCursor();

		while (c.moveToNext()) {
			int downloadid = c.getInt((c.getColumnIndex("downloadid")));
			if ( downloadid > 0){
				mgr.remove(downloadid);
			}
		}
	}

	public String getLocalAppUpdateInfo() {
		String info = "";

		Cursor c = queryTheCursor();
		StringBuilder builder = new StringBuilder();  
		int appAction = 0;
		while(c.moveToNext()){
			builder.delete( 0, builder.length());
			appAction = c.getInt(c.getColumnIndex("action"));
			
			if(appAction == 1 || appAction == 2){
				if(!(c.getInt(c.getColumnIndex("updateSuccess")) == 0)){
					break;
				}
				builder.append("*");
			}else if (appAction == 3 || appAction == 4) {
				builder.append("-");
			}
			builder.append(c.getString(c.getColumnIndex("appName")));
			if(appAction == 1 || appAction == 2){
				builder.append("应用更新").append("\n");

			}else if (appAction == 3) {
				builder.append("应用卸载").append("\n");
			}else if (appAction == 4) {
				builder.append("应用仅卸载").append(c.getString(c.getColumnIndex("verCode")))
				.append("版本\n");
			}
			info += builder.toString();
		}
		Log.d(TAG, "getLocalAppUpdateInfo： info is " + info);
		return info;
	}
}
